﻿using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace VioletDevelopmentLaboratory.Net.Web
{
	public class ImageManager
	{
		public static Image CreateThumbnailImage(String imageFilePath, Boolean keepOriginalSizeRatio, Int32 thumbnailMaxWidth,
			Int32 thumbnailMaxHeight)
		{
			Int32 thumbnailWidth = 0;
			Int32 thumbnailHeight = 0;
			Image thumbnailImage = null;

			using (Bitmap originalBitMap = new Bitmap(imageFilePath))
			{
				getThumbnailSize(originalBitMap.Width, originalBitMap.Height, keepOriginalSizeRatio, thumbnailMaxWidth, thumbnailMaxHeight, out thumbnailWidth, out thumbnailHeight);

				thumbnailImage = originalBitMap.GetThumbnailImage(thumbnailWidth, thumbnailHeight, null, IntPtr.Zero);
			}

			return thumbnailImage;
		}

		public static String CreateThumbnailImageFile(String imageFilePath, Boolean keepOriginalSizeRatio, Int32 thumbnailMaxWidth,
			Int32 thumbnailMaxHeight)
		{
			Int32 thumbnailWidth = 0;
			Int32 thumbnailHeight = 0;
			String saveImageFilePath = String.Empty;

			using (Bitmap originalBitMap = new Bitmap(imageFilePath))
			{
				getThumbnailSize(originalBitMap.Width, originalBitMap.Height, keepOriginalSizeRatio, thumbnailMaxWidth, thumbnailMaxHeight, out thumbnailWidth, out thumbnailHeight);
			}

			using (Image sourceImage = Image.FromFile(imageFilePath))
			{
				using (Bitmap bitmap = new Bitmap(sourceImage, new Size(thumbnailWidth, thumbnailHeight)))
				{
					saveImageFilePath = imageFilePath;
					saveImageFilePath = saveImageFilePath + ".t." + ImageFormat.Jpeg.ToString();
					bitmap.Save(saveImageFilePath, ImageFormat.Jpeg);
				}
			}
			
			return saveImageFilePath;
		}

		private static void getThumbnailSize(Int32 originalWidth, Int32 originalHeight, Boolean keepOriginalSizeRatio, Int32 thumbnailMaxWidth, Int32 thumbnailMaxHeight, out Int32 thumbnailWidth, out Int32 thumbnailHeight)
		{
			if (keepOriginalSizeRatio)
			{
				thumbnailWidth = originalWidth;
				thumbnailHeight = originalHeight;
				Single ratio = (((Single)originalHeight) / ((Single)originalWidth)) * 100f;
				if (ratio < 100f)
				{
					if (originalWidth > thumbnailMaxWidth)
					{
						thumbnailWidth = thumbnailMaxWidth;
						thumbnailHeight = (originalHeight * thumbnailMaxWidth) / originalWidth;
					}
				}
				else if (originalHeight > thumbnailMaxHeight)
				{
					thumbnailWidth = (originalWidth * thumbnailMaxHeight) / originalHeight;
					thumbnailHeight = thumbnailMaxHeight;
				}
			}
			else
			{
				thumbnailWidth = thumbnailMaxWidth;
				thumbnailHeight = thumbnailMaxHeight;
			}
		}
	}
}
